import 'package:flutter/material.dart';

final routerObserver = MyRouterObserver();

class MyRouterObserver extends RouteObserver<PageRoute> {
  final List<Route<dynamic>> _activeRoutes = [];
  final List<NavigatorObserver> listeners = [];

  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPush(route, previousRoute);
    _activeRoutes.add(route);
    for(final l in listeners) {
      l.didPush(route, previousRoute);
    }
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPop(route, previousRoute);
    _activeRoutes.remove(route);
    for(final l in listeners) {
      l.didPop(route, previousRoute);
    }

  }

  @override
  void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
    _activeRoutes.remove(route);
    for(final l in listeners) {
      l.didRemove(route, previousRoute);
    }

  }

  @override
  /// The [Navigator] replaced `oldRoute` with `newRoute`.
  void didReplace({ Route<dynamic>? newRoute, Route<dynamic>? oldRoute }) {
    for(final l in listeners) {
      l.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    }
  }

  Route<dynamic> top() {
    return _activeRoutes.last;
  }

  Route<dynamic>? beforeOf(String routePath) {
    try {
      final index = _activeRoutes.indexWhere((element) => element.settings.name == routePath);
      if (index - 1 < 0) {
        return null;
      }
      return _activeRoutes[index - 1];
    } on StateError catch(e) {
      debugPrint(e.toString());
    }

    return null;
  }

  /// 获取路由的激活状态
  bool isRouteActive(String routeName) {
    return _activeRoutes.any((route) => route.settings.name == routeName);
  }

  List<Route<dynamic>> get activeRoutes => _activeRoutes;

  addListener(NavigatorObserver listener) {
    listeners.add(listener);
  }

  removeListener(NavigatorObserver listener) {
    listeners.remove(listener);
  }
}